package top.yaofengqiao.springcloudsimple.tenant.starter.xxljob;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import top.yaofengqiao.springcloudsimple.tenant.starter.service.ITenantService;
import top.yaofengqiao.springcloudsimple.tenant.starter.util.TenantContextHolder;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author yfq
 * @date 2024/8/12 16:01
 * @description 多租户job切面
 */
@Aspect
@Component
public class TenantJobAspect {
    @Resource
    private ITenantService tenantService;
    @Resource
    private ThreadPoolExecutor tenantThreadPoolExecutor;

    @Around("@annotation(top.yaofengqiao.springcloudsimple.tenant.starter.xxljob.TenantJob)")
    public void executeTenantJob(ProceedingJoinPoint joinPoint) {
        // 1. 获取所有租户
        List<Long> tenants = tenantService.getAllTenant();

        if (CollectionUtils.isEmpty(tenants)) return;

        // 2. 对所有租户执行job任务
        for (Long tenant : tenants) {
            tenantThreadPoolExecutor.execute(() -> {
                try {
                    TenantContextHolder.setTenant(tenant);

                    // 3. 执行对应job
                    joinPoint.proceed();
                } catch (Throwable ignored) {
                } finally {
                    TenantContextHolder.clear();
                }
            });
        }
    }

}
